/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.controller;

import com.alibaba.fastjson.JSONArray;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.emergency.domain.EmergencyResponse;
import com.koron.emergency.domain.NoticeBean;
import com.koron.emergency.service.api.EmergencyResponseService;
import com.koron.emergency.util.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "emergencyResponse", description = "应急响应接口类")
@RestController
@RequestMapping("/emergencyResponse")
public class EmergencyResponseController {
    private final static Logger log = LoggerFactory.getLogger(EmergencyResponseController.class);
    @Autowired
    private EmergencyResponseService responseService;


    @ApiOperation("保存应急响应接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanId", value = "应急预案id",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "responseLevel", value = "响应等级，0一级、1二级，2三级,3-四级",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "responseLevelName", value = "响应等级名称",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "beginTime", value = "开始日期，格式为：yyyy-MM-dd HH:mm:ss",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间，格式为：yyyy-MM-dd HH:mm:ss",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "url", value = "链接地址",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "notices", value = "通知相关信息(JSON格式字符串)", required = true, paramType = "query", dataType = "String"),
    })
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    @Log(title = "保存应急响应", businessModule = "应急响应", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore EmergencyResponse bean, String notices) {
        MessageBean<Integer> messageBean = new MessageBean<>();
        if (null == user) {
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        if (StringUtils.isEmpty(notices)){
            messageBean.setCode(BusinessCode.FAILURE.getCode());
            messageBean.setDescription("应急响应通知信息不能为空");
            return messageBean;
        }
        // 通知信息
        List<NoticeBean> beanList = JSONArray.parseArray(notices, NoticeBean.class);
        for (NoticeBean noticeBean : beanList) {
            if (StringUtils.isEmpty(noticeBean.getExtraObject())|| StringUtils.isEmpty(noticeBean.getExtraObjectName())){
                messageBean.setCode(BusinessCode.FAILURE.getCode());
                messageBean.setDescription("通知人不能为空");
                return messageBean;
            }
            if (StringUtils.isEmpty(noticeBean.getContent())){
                messageBean.setCode(BusinessCode.FAILURE.getCode());
                messageBean.setDescription("通知内容不能为空");
                return messageBean;
            }
        }
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        bean.setUpdateTime(new Date());
        return responseService.save(user, bean,beanList);
    }

    @ApiOperation("删除应急响应接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "应急响应id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "approver", value = "审批人", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    @Log(title = "删除应急响应", businessModule = "应急响应", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Integer> deleteEmergency(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {

        if (null == user)
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), Integer.class);
        return responseService.delete(user, id);
    }

    @ApiOperation("查询单个应急响应详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "应急响应id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.POST)
    public MessageBean<EmergencyResponse> details(@RequestParam final String id) {

        return responseService.queryOne(id);
    }

    @ApiOperation("应急响应列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<EmergencyResponse>> list(@RequestParam(required = false) final String corpCode,
                                                         @RequestParam Integer page, @RequestParam Integer pageSize) {
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<EmergencyResponse>> msg = responseService.list(corpCode, start, pageSize);
        if (null != msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }


    @ApiOperation("应急响应列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
      })
    @RequestMapping(value = "/exportList.htm", method = RequestMethod.GET)
    public HttpEntity<?> exportList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String corpCode) {
        if (null == user) {
            return null;
        }
        List<EmergencyResponse> list = responseService.exportList(user, corpCode);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);

        File targetFile = new File("static/excel/emergencyResponseList.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/emergencyResponseList.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Excel.createFile("应急响应列表", targetFile, "emergencyResponseList.btl", map);
    }
}
